//
//  NSMutableDictionary+Safe.m
//  CommonTool
//
//  Created by Name i on 2022/4/14.
//

#import "NSMutableDictionary+Safe.h"

@implementation NSMutableDictionary (Safe)

+ (void)exchangeMethod {

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Class dictionaryM = NSClassFromString(@"__NSDictionaryM");
        
        //setObject:forKey:
        [NSObject tnSwizzlingInstanceMethod: @selector(setObject:forKey:)
                                 withMethod: @selector(safe_setObject:forKey:)
                                  withClass: dictionaryM];
        
        //setObject:forKeyedSubscript:
        if (@available(iOS 11.0, *)) {
            [NSObject tnSwizzlingInstanceMethod:@selector(setObject:forKeyedSubscript:)
                                     withMethod:@selector(safe_setObject:forKeyedSubscript:)
                                      withClass:dictionaryM];
        }
                
        // removeObjectForKey:
        [NSObject tnSwizzlingInstanceMethod:@selector(removeObjectForKey:)
                                 withMethod:@selector(safe_removeObjectForKey:)
                                  withClass:dictionaryM];
    });
}


- (void)safe_setObject:(id)anObject forKey:(id<NSCopying>)aKey {
    @try {
        [self safe_setObject:anObject forKey:aKey];
    }
    @catch (NSException *exception) {
        [NNDefender crashWithException:exception defaultToDo:    NNDefenderDefaultIgnore];
    }
    @finally {
        
    }
}

- (void)safe_setObject:(id)obj forKeyedSubscript:(id<NSCopying>)key {
    @try {
        [self safe_setObject:obj forKeyedSubscript:key];
    }
    @catch (NSException *exception) {
        [NNDefender crashWithException:exception defaultToDo:    NNDefenderDefaultIgnore];
    }
    @finally {
        
    }
}


- (void)safe_removeObjectForKey:(id)aKey {
    @try {
        [self safe_removeObjectForKey:aKey];
    }
    @catch (NSException *exception) {
        [NNDefender crashWithException:exception defaultToDo:    NNDefenderDefaultIgnore];
    }
    @finally {
        
    }
}



@end
